package br.com.covosys.jsf;

import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import br.com.covosys.model.bean.Usuario;
import br.com.covosys.util.JSFUtils;

@SuppressWarnings("serial")
public class CovoSYSAuthorizationListener implements PhaseListener {

	@Override
	public void afterPhase(PhaseEvent phaseEvent) {
		
	}

	@Override
	public void beforePhase(PhaseEvent phaseEvent) {
		
		HttpServletRequest httpServletRequest = JSFUtils.getHttpServletRequest();
		
		if (!(httpServletRequest.getRequestURI().indexOf("login.faces") > -1)) {
			
			HttpSession httpSession = JSFUtils.getSession();
			
			Usuario usuario = (Usuario) httpSession.getAttribute("usuario");
			
			if (usuario == null) {
				FacesContext facesContext = FacesContext.getCurrentInstance();
				JSFUtils.redirect(JSFUtils.getHttpServletRequest().getContextPath()+"/login/login.faces");
				facesContext.responseComplete();
			}
			
		}		
	}

	@Override
	public PhaseId getPhaseId() {
		return PhaseId.RESTORE_VIEW;
	}
}
